<?php

namespace alibaba;

use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationRequest;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
use Exception;
use think\Log;

class Check
{
    public $accessKeyId = 'LTAI5tJVdRTYyinUCKWPBsVQ';
    public $accessKeySecret = 'PuG5cemUw4EjG0Hrdpveazo687ncLr';
    // 接入区域和地址请根据实际情况修改
    public $endpoint = "green-cip.cn-shanghai.aliyuncs.com";


    /**
     * 创建请求客户端
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return Green
     */
    function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
            // 设置HTTP代理。
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // 设置HTTPS代理。
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }


    //字符串检测
    public function textCheck($content,$service="chat_detection") {
        $request = new TextModerationRequest;
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        $request->service = $service;
        // 待检测数据。
        $arr = array('content' => $content);
        $request->serviceParameters = json_encode($arr);
        if (empty($content)) {
            return "内容不能为空";
        }

        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$this->endpoint);

        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);

        try {
            // 调用接口，获取检测结果。
            $response = $client->textModerationWithOptions($request, $runtime);
            // 自动路由。
            if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
                //服务端错误，区域切换到cn-beijing
                $endpoint = "green-cip.cn-beijing.aliyuncs.com";

                $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$endpoint);
                $response = $client->textModerationWithOptions($request, $runtime);
            }
            $data = json_encode($response->body,true);
            $data = json_decode($data,true);
//            dump($data);
            if (!empty($data["data"]["reason"])) {
                return json_decode($data["data"]["reason"],true)["riskTips"];
            }
            return "";

        } catch (Exception $e) {
            return $e->getMessage();
//            var_dump($e->getMessage());
//            var_dump($e->getErrorInfo());
//            var_dump($e->getLastException());
//            var_dump($e->getLastRequest());
        }
    }

    //图片检测
    public function imageCheck($content) {
        $request = new TextModerationRequest;
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        $request->service = "baselineCheck";
        // 待检测数据。
        $arr = array(

            // 待检测图片，公网可访问的URL。
            'imageUrl' => $content,
            // 检测数据唯一标识。
            'dataId' => uniqid()
        );
        $request->serviceParameters = json_encode($arr);
        if (empty($content)) {
            return "内容不能为空";
        }

        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$this->endpoint);

        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);

        try {
            // 调用接口，获取检测结果。
            $response = $client->imageModerationWithOptions($request, $runtime);
            // 自动路由。
            if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
                //服务端错误，区域切换到cn-beijing
                $endpoint = "green-cip.cn-beijing.aliyuncs.com";

                $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$endpoint);
                $response = $client->imageModerationWithOptions($request, $runtime);
            }
            $data = json_encode($response->body,true);
            Log::record("图片审核：".$data, 'info');
            $data = json_decode($data,true);

            $RiskLevel["high"] = "高风险";
            $RiskLevel["medium"] = "中风险";
            $RiskLevel["low"] = "低风险";
            $RiskLevel["none"] = "未检测到风险";

            $result = $data["data"]["result"];
            if (is_array($result)) {
                foreach($result as $v){
                    if (array_key_exists("confidence", $v)) {
                        if ($v["confidence"] > 95.00) {
                             return $RiskLevel[$data["data"]["riskLevel"]];
                        }
                    }

                }
            }

//             if ($data["data"]["riskLevel"] != "none" && $data["data"]["riskLevel"] != "low" && $data["data"]["riskLevel"] != "medium") {
//                             return $RiskLevel[$data["data"]["riskLevel"]];
//                         }

//             if ($data["data"]["riskLevel"] != "none" && $data["data"]["riskLevel"] != "low" && $data["data"]["riskLevel"] != "medium") {
//                 return $RiskLevel[$data["data"]["riskLevel"]];
//             }
            return "";

        } catch (Exception $e) {
            return "";
//            var_dump($e->getMessage());
//            var_dump($e->getErrorInfo());
//            var_dump($e->getLastException());
//            var_dump($e->getLastRequest());
        }
    }

    //视频检测
    public function videoCheck($content) {
        $request = new TextModerationRequest;
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        $request->service = "videoDetection";
        // 待检测数据。
        $arr = array(

            // 待检测图片，公网可访问的URL。
            'url' => $content,
            // 检测数据唯一标识。
            'dataId' => uniqid()
        );
        $request->serviceParameters = json_encode($arr);
        if (empty($content)) {
            return "内容不能为空";
        }

        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$this->endpoint);

        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);

        try {
            // 调用接口，获取检测结果。
            $response = $client->videoModerationWithOptions($request, $runtime);
            // 自动路由。
            if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
                //服务端错误，区域切换到cn-beijing
                $endpoint = "green-cip.cn-beijing.aliyuncs.com";

                $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$endpoint);
                $response = $client->videoModerationWithOptions($request, $runtime);
            }
            $data = json_encode($response->body,true);
            $data = json_decode($data,true);

            return $data["data"]["taskId"];

        } catch (Exception $e) {
            return $e->getMessage();
//            var_dump($e->getMessage());
//            var_dump($e->getErrorInfo());
//            var_dump($e->getLastException());
//            var_dump($e->getLastRequest());
        }
    }

    //视频审核结果查询
    public function videoModerationResult($content) {
        $request = new TextModerationRequest;
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        $request->service = "videoDetection";
        // 待检测数据。
        $arr = array(
            'taskId' => $content,
        );
        $request->serviceParameters = json_encode($arr);
        if (empty($content)) {
            return "内容不能为空";
        }

        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$this->endpoint);

        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);

        try {
            // 调用接口，获取检测结果。
            $response = $client->videoModerationResultWithOptions($request, $runtime);
            // 自动路由。
            if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
                //服务端错误，区域切换到cn-beijing
                $endpoint = "green-cip.cn-beijing.aliyuncs.com";

                $client = $this->create_client($this->accessKeyId,$this->accessKeySecret,$endpoint);
                $response = $client->videoModerationResultWithOptions($request, $runtime);
            }
            $data = json_encode($response->body,true);
            $data = json_decode($data,true);

            return $data;

        } catch (Exception $e) {
            return $e->getMessage();
//            var_dump($e->getMessage());
//            var_dump($e->getErrorInfo());
//            var_dump($e->getLastException());
//            var_dump($e->getLastRequest());
        }
    }



}